<?php

namespace App\Console\Commands\Command\Init;

use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Str;

class InitAes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'aes:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化aes key & iv';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws FileNotFoundException
     */
    public function handle()
    {
        $key = Str::random();
        $iv  = Str::random();

        $this->save('AES_KEY', $key);
        $this->save('AES_IV', $iv);
    }

    /**
     * @throws FileNotFoundException
     */
    private function save($key, $value)
    {
        $path = $this->envPath();
        if (!file_exists($path)) {
            throw new FileNotFoundException("env not exist");
        }

        if (Str::contains(file_get_contents($path), $key) === false) {
            // create new entry
            file_put_contents($path, PHP_EOL."{$key}=$value".PHP_EOL, FILE_APPEND);
            $this->info("{$key} : [$value] set successfully.");
        } else {
            $this->comment("配置{$key}已存在");
            return;
        }
    }

    /**
     * Get the .env file path.
     *
     * @return string
     */
    protected function envPath(): string
    {
        if (method_exists($this->laravel, 'environmentFilePath')) {
            return $this->laravel->environmentFilePath();
        }

        // check if laravel version Less than 5.4.17
        if (version_compare($this->laravel->version(), '5.4.17', '<')) {
            return $this->laravel->basePath().DIRECTORY_SEPARATOR.'.env';
        }

        return $this->laravel->basePath('.env');
    }
}
